/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;


public class UrsusLoader {
	private static final String LIB_PATH = "lib";
	private static final String LIB_APP_PATH = "lib-app";
    private URLClassLoader frameworkLoader;
	private URLClassLoader applicationLoader;

	URLClassLoader getFrameworkLoader() {
		return frameworkLoader;
	}
	
	URLClassLoader getApplicationLoader() {
		return applicationLoader;
	}
	
	void load() throws MalformedURLException {
		loadFramework(ClassLoader.getSystemClassLoader());
		loadApplication(frameworkLoader);
	}
	
	private void loadFramework(ClassLoader parentLoader) throws MalformedURLException {
		File[] libList = new File(LIB_PATH).listFiles();
        URL[] frameworkUrls = new URL[libList.length];
		for (int i = 0; i < libList.length; i++) {
			frameworkUrls[i] =
				new URL("jar:file://"
						+ libList[i].getAbsolutePath()
						+ "!/");
		}
        frameworkLoader = new URLClassLoader(frameworkUrls, parentLoader);
	}
	
	private void loadApplication(ClassLoader parentLoader) throws MalformedURLException {
		File[] libList = new File(LIB_APP_PATH).listFiles();
        URL[] applicatoinUrls = new URL[libList.length];
		for (int i = 0; i < libList.length; i++) {
			applicatoinUrls[i] =
				new URL("jar:file://"
						+ libList[i].getAbsolutePath()
						+ "!/");
		}
        applicationLoader = new URLClassLoader(applicatoinUrls, parentLoader);
	}
}
